package com.pj.startactivityforresult;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;

import java.util.List;
import java.util.Map;
import java.util.Set;

@RequiresApi(api = Build.VERSION_CODES.Q)
public class TakePhoto extends AppCompatActivity {
    private Button requestPermission;
    private Button requestPermissions;
    private Button selectPhoto;
    private Button takePhotoBitmap;
    private Button takePhotoUri;
    private Button readContacts;
    private Button selectDoc;
    private Button selectDocs;
    private Button selectTree;
    private LinearLayout body;
    private Button selectPhotos;
    private Button selectMany;
    private ActivityResultLauncher<String> permissionResult;
    private ActivityResultLauncher<String[]> permissionsResult;
    private ActivityResultLauncher<String[]> selectPhotoResult;
    private ActivityResultLauncher<String[]> selectPhotosResult;
    private ActivityResultLauncher<Void> takePhotoBitmapResult;
    private ActivityResultLauncher<Uri> takePhotoResult;
    private ActivityResultLauncher<Void> readContactsResult;
    private ActivityResultLauncher<String[]> selectTextResult;
    private ActivityResultLauncher<String[]> selectTextsResult;
    private ActivityResultLauncher<Uri> selectTreeResult;
    private ActivityResultLauncher<String[]> selectManyResult;
    private Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo);
        initView();
        initRegisterActivity();
    }

    private void initRegisterActivity() {
        permissionResult = registerForActivityResult(new ActivityResultContracts.RequestPermission(), new ActivityResultCallback<Boolean>() {
            @Override
            public void onActivityResult(Boolean result) {
                if (result) {
                    Toast.makeText(TakePhoto.this, "您同意了该权限", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(TakePhoto.this, "您拒绝了该权限", Toast.LENGTH_SHORT).show();
                }
            }
            //在这里加入你要请求的权限
        });
        //为了更好的理解这个回调 没有简写成lambda表达式
        permissionsResult = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
            @Override
            public void onActivityResult(Map<String, Boolean> result) {
                Set<Map.Entry<String, Boolean>> set = result.entrySet();
                for (Map.Entry<String, Boolean> item : set) {
                    switch (item.getKey()) {
                        case Manifest.permission.CAMERA: {
                            showMsg(item, "相机");
                            break;
                        }
                        case Manifest.permission.WRITE_EXTERNAL_STORAGE: {
                            showMsg(item, "读写");
                            break;
                        }
                        case Manifest.permission.READ_CONTACTS: {
                            showMsg(item, "读取通讯录");
                            break;
                        }
                    }
                }
            }
        });
        selectPhotoResult = registerForActivityResult(new ActivityResultContracts.OpenDocument(), new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                ImageView imageView = getImageView();
                addView(imageView);
                Glide.with(TakePhoto.this).load(result).into(imageView);
            }
        });
        selectPhotosResult = registerForActivityResult(new ActivityResultContracts.OpenMultipleDocuments(), new ActivityResultCallback<List<Uri>>() {
            @Override
            public void onActivityResult(List<Uri> result) {
                if (result != null && result.size() != 0) {
                    GridView gridView = new GridView(TakePhoto.this);
                    gridView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    gridView.setNumColumns(2);
                    gridView.setAdapter(new MyAdapter(result));
                    addView(gridView);
                    Toast.makeText(TakePhoto.this, ""+result.size(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(TakePhoto.this, "你没有选择任何图片", Toast.LENGTH_SHORT).show();
                }
            }
        });
        takePhotoBitmapResult = registerForActivityResult(new ActivityResultContracts.TakePicturePreview(), new ActivityResultCallback<Bitmap>() {
            @Override
            public void onActivityResult(Bitmap result) {
                ImageView imageView = getImageView();
                imageView.setImageBitmap(result);
                addView(imageView);
            }
            //因为只需要获得预览图
        });
        takePhotoResult = registerForActivityResult(new ActivityResultContracts.TakePicture(), new ActivityResultCallback<Boolean>() {
            @Override
            public void onActivityResult(Boolean result) {
                if (result) {
                    ImageView imageView = getImageView();
                    Glide.with(TakePhoto.this).load(uri).into(imageView);
                    Log.d("takePhotoUri", uri.getPath());
                    addView(imageView);
                } else {
                    //没有拍照
                    Toast.makeText(TakePhoto.this, "没有拍摄照片", Toast.LENGTH_SHORT).show();
                }
            }
        });
        readContactsResult = registerForActivityResult(new ActivityResultContracts.PickContact(), new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                //but为啥还要用ContentResolver...害
                if (result != null) {
                    Cursor query = getContentResolver().query(result, null, null, null);
                    if (query.moveToFirst()) {
                        @SuppressLint("Range") String name = query.getString(query.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        @SuppressLint("Range") String number = query.getString(query.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                        Toast.makeText(TakePhoto.this, "联系人名称:" + name + "\n" + "电话号码：" + number, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        selectTextResult = registerForActivityResult(new ActivityResultContracts.OpenDocument(), new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                //我暂时也不知道拿到uri之后应该干些啥坏事
                Toast.makeText(TakePhoto.this, result.getPath(), Toast.LENGTH_SHORT).show();
            }
        });
        selectTextsResult = registerForActivityResult(new ActivityResultContracts.OpenMultipleDocuments(), new ActivityResultCallback<List<Uri>>() {
            @Override
            public void onActivityResult(List<Uri> result) {
                //就显示拿了几个吧
                Toast.makeText(TakePhoto.this, "" + result.size(), Toast.LENGTH_SHORT).show();
            }
        });
        selectTreeResult = registerForActivityResult(new ActivityResultContracts.OpenDocumentTree(), new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                //提示用户选择一个目录，并返回用户选择的作为一个Uri返回，应用程序可以完全管理返回目录中的文档。
                Toast.makeText(TakePhoto.this, result.getPath(), Toast.LENGTH_SHORT).show();
            }
        });
        selectManyResult = registerForActivityResult(new ActivityResultContracts.OpenMultipleDocuments(), new ActivityResultCallback<List<Uri>>() {
            @Override
            public void onActivityResult(List<Uri> result) {
                Toast.makeText(TakePhoto.this, "" + result.size(), Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void initView() {
        requestPermission = (Button) findViewById(R.id.request_permission);
        requestPermissions = (Button) findViewById(R.id.request_permissions);
        selectPhoto = (Button) findViewById(R.id.select_photo);
        selectPhotos = (Button) findViewById(R.id.select_photos);
        takePhotoBitmap = (Button) findViewById(R.id.take_photo_bitmap);
        takePhotoUri = (Button) findViewById(R.id.take_photo_uri);
        readContacts = (Button) findViewById(R.id.read_contacts);
        selectDoc = (Button) findViewById(R.id.select_doc);
        selectDocs = (Button) findViewById(R.id.select_docs);
        selectTree = (Button) findViewById(R.id.select_tree);
        selectMany = (Button) findViewById(R.id.select_many);
        body = (LinearLayout) findViewById(R.id.body);

        //获取单个权限
        requestPermission.setOnClickListener(view -> {
            permissionResult.launch(Manifest.permission.CAMERA);
        });

        //获取多个权限
        requestPermissions.setOnClickListener(view -> {
            //在这里加入你要请求的权限列表，为String[]的形式，和老版本差不多
            permissionsResult.launch(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CONTACTS});
        });

        //选择一张图片
        selectPhoto.setOnClickListener(view -> {
           selectPhotoResult.launch(new String[]{"image/*"});
        });
        //选择多张图片
        selectPhotos.setOnClickListener(view -> {
            selectPhotosResult.launch(new String[]{"image/*"});
        });

        //获得拍照图片预览图
        takePhotoBitmap.setOnClickListener(view -> {
            takePhotoBitmapResult.launch(null);
        });

        //拍摄照片并获得Uri
        takePhotoUri.setOnClickListener(view -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                ContentValues contentValues = new ContentValues();
                contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "测试图片.jpg");
                contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
                uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                takePhotoResult.launch(uri);
            } else {
                //写过比这个版本底的拍照获取图片方式QAQ
                Toast.makeText(this, "版本太低自行适配滑稽", Toast.LENGTH_SHORT).show();
            }
        });

        //读取联系人
        readContacts.setOnClickListener(view -> {
           readContactsResult.launch(null);
        });

        //选择一个文本文件
        selectDoc.setOnClickListener(view -> {
            selectTextResult.launch(new String[]{"text/plain"});
        });

        //选择多个文本文件
        selectDocs.setOnClickListener(view -> {
           selectTextsResult.launch(new String[]{"text/plain"});
        });

        //选择一个目录
        selectTree.setOnClickListener(view -> {
            //我也暂时不知道这个目录用来干嘛QAQ
            //selectTreeResult.launch();

        });

        //选择多种文件
        selectMany.setOnClickListener(view -> {
            selectManyResult.launch(new String[]{"image/*","text/plain"});
        });

    }

    private void addView(View view) {
        body.addView(view);
        new Handler().postDelayed(() -> {
            body.removeView(view);
        }, 10000);
    }

    private void showMsg(Map.Entry<String, Boolean> item, String name) {
        if (item.getValue()) {
            Toast.makeText(this, name + "权限获取成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, name + "权限获取失败", Toast.LENGTH_SHORT).show();
        }
    }

    private ImageView getImageView() {
        ImageView imageView = new ImageView(TakePhoto.this);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        return imageView;
    }

    class MyAdapter extends BaseAdapter {

        List<Uri> data;

        public MyAdapter(List<Uri> data) {
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            @SuppressLint("ViewHolder") View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.grid_view_item, null);
            ImageView imageView = v.findViewById(R.id.image_view);
            Glide.with(viewGroup.getContext()).load(data.get(i)).into(imageView);
            return v;
        }
    }

}